﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Clipping.Infrastructure.Models;
using System.Windows.Input;
using System.Windows;
namespace ClippingMaster
{
    public class KeywordsPanelViewModel : GalaSoft.MvvmLight.ViewModelBase
    {
        public event Action<KeywordInfo> OnKeywordSearch;


        private KeywordsRepository rep = new KeywordsRepository();
        public KeywordsPanelViewModel()
        {
            initCommands();
            initData();

        }






        private void initData()
        {
            var allCategories = rep.GetAllCategories();
            var allKeywords = rep.GetAllKeywords();

            KeywordCategory rootCategory = new KeywordCategory() { Id = Guid.Empty, Name = "关键词列表" };
            KeywordCategoryModel kcm = new KeywordCategoryModel() { Category = rootCategory };
            populate(kcm, allCategories, allKeywords);
            this.AllKeywords = new ObservableCollection<KeywordCategoryModel>() { kcm };
        }

        private void populate(KeywordCategoryModel categoryModel, IEnumerable<KeywordCategory> allCategories, IEnumerable<KeywordInfo> allKeywords)
        {
            if (allCategories != null)
            {
                var subCategories = allCategories.Where(c => c.ParentId == categoryModel.Category.Id).ToList();

                if (subCategories != null)
                {

                    foreach (var sub in subCategories)
                    {
                        KeywordCategoryModel kcm = new KeywordCategoryModel() { Category = sub, ParentCategory = categoryModel };
                        populate(kcm, allCategories, allKeywords);
                        categoryModel.SubCategoriesAndKeywords.Add(kcm);
                    }
                }
            }
            if (allKeywords != null)
            {
                var keywords = allKeywords.Where(k => k.CategoryId == categoryModel.Category.Id).ToList();
                if (keywords != null && keywords.Count > 0)
                {
                    foreach (var k in keywords)
                    {
                        KeywordModel km = new KeywordModel() { Keyword = k, Category = categoryModel };
                        categoryModel.SubCategoriesAndKeywords.Add(km);
                    }
                }
            }

        }

        private void initCommands()
        {
            //throw new NotImplementedException();
            this.AddCategoryCommand = new GalaSoft.MvvmLight.Command.RelayCommand<object>(addCategory);
            this.AddKeywordCommand = new GalaSoft.MvvmLight.Command.RelayCommand<object>(addKeyword);
            this.DeleteCategoryCommand = new GalaSoft.MvvmLight.Command.RelayCommand<object>(deleteCategory);
            this.DeleteKeywordCommand = new GalaSoft.MvvmLight.Command.RelayCommand<KeywordModel>(deleteKeywod);
            this.ModifyCategoryCommand = new GalaSoft.MvvmLight.Command.RelayCommand<object>(modifyCategory);
            this.ModifyKeywordCommand = new GalaSoft.MvvmLight.Command.RelayCommand<KeywordModel>(modifyKeyword);
            this.SearchCommand = new GalaSoft.MvvmLight.Command.RelayCommand<KeywordModel>(search);
        }

       

        private void addCategory(object categoryModel)
        {
            KeywordCategoryModel kc = categoryModel as KeywordCategoryModel;
            if (kc == null)
                kc = this.AllKeywords.FirstOrDefault();
            if (kc == null)
                return;
            KeywordsCategorySettingViewModel vm = new KeywordsCategorySettingViewModel(kc.Category.Id);
            KeywordsCategorySetting win = new KeywordsCategorySetting(vm);

            vm.OnSaved += () =>
            {
                KeywordCategoryModel newKcm = new KeywordCategoryModel()
                {
                    Category = vm.Category,
                    ParentCategory =kc
                };
                kc.SubCategoriesAndKeywords.Add(newKcm);
                win.Close();
            };
            vm.OnCanceled += () =>
            {
                win.Close();
            };
            win.ShowDialog();
        }

        private void addKeyword(object categoryModel)
        {
            KeywordCategoryModel kc = categoryModel as KeywordCategoryModel;
            if (kc == null)
                kc = this.AllKeywords.FirstOrDefault();
            if (kc == null)
                return;


            KeywordSettingViewModel vm = new KeywordSettingViewModel(kc.Category);
            KeywordSetting win = new KeywordSetting(vm);

            vm.OnSaved += () =>
            {
                kc.SubCategoriesAndKeywords.Add(new KeywordModel() { Keyword = vm.KeywordInfo, Category = kc });
                win.Close();
            };
            vm.OnCanceled += () =>
            {
                win.Close();
            };
            win.ShowDialog();
        }

        private void deleteCategory(object categoryModelObj)
        {

            KeywordCategoryModel categoryModel = categoryModelObj as KeywordCategoryModel;
            if (categoryModel==null || categoryModel == this.AllKeywords.First())
                return;
            
            if (MessageBox.Show(string.Format("确实要删除分类{0}及其下所有关键词吗？", categoryModel.Category.Name), "删除分类", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                KeywordsRepository rep = new KeywordsRepository();
                bool succeed = rep.DelCategory(categoryModel.Category.Id);
                if (succeed)
                {
                    if (categoryModel.ParentCategory != null)
                        categoryModel.ParentCategory.SubCategoriesAndKeywords.Remove(categoryModel);
                }
                else
                {
                    MessageBox.Show("删除失败");
                }

            }
        }

        private void deleteKeywod(KeywordModel keywordModel)
        {
            if (keywordModel == null)
                return;

            if (MessageBox.Show(string.Format("确实要删除关键词{0}吗？", keywordModel.Keyword.Keyword), "删除关键词", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                KeywordsRepository rep = new KeywordsRepository();
                bool succeed = rep.DeleteKeyword(keywordModel.Keyword);
                if (succeed)
                {
                    keywordModel.Category.SubCategoriesAndKeywords.Remove(keywordModel);
                }
                else 
                {
                    MessageBox.Show("删除失败");
                }

            }
        }
        private void search(KeywordModel keywordModel)
        {
            if (keywordModel == null)
                return;
            var handler = this.OnKeywordSearch;
            if (handler != null)
            {
                handler(keywordModel.Keyword);
            
            }
        }



        private void modifyCategory(object categoryModelObj)
        {
            KeywordCategoryModel kc = categoryModelObj as KeywordCategoryModel;
            if (kc == null || kc == this.AllKeywords.FirstOrDefault())
                return;
            KeywordsCategorySettingViewModel vm = new KeywordsCategorySettingViewModel(kc.Category);
            KeywordsCategorySetting win = new KeywordsCategorySetting(vm);

            vm.OnSaved += () =>
            {
                kc.Category = vm.Category;
                win.Close();
            };
            vm.OnCanceled += () =>
            {
                win.Close();
            };
            win.ShowDialog();
        }

        private void modifyKeyword(KeywordModel keywordModel)
        {
            if (keywordModel == null)
                return;
            KeywordSettingViewModel vm = new KeywordSettingViewModel(keywordModel.Keyword);
            KeywordSetting win = new KeywordSetting(vm);

            vm.OnSaved += () =>
            {
                keywordModel.Keyword = vm.KeywordInfo;
                win.Close();
            };
            vm.OnCanceled += () =>
            {
                win.Close();
            };
            win.ShowDialog();
        }


        private ObservableCollection<KeywordCategoryModel> _allKeywords;
        public ObservableCollection<KeywordCategoryModel> AllKeywords
        {
            get
            {
                return _allKeywords;
            }
            set
            {
                if (value == _allKeywords)
                    return;
                _allKeywords = value;
                RaisePropertyChanged(() => this.AllKeywords);
            }
        }


        public ICommand AddKeywordCommand { get; set; }
        public ICommand ModifyKeywordCommand { get; set; }


        public ICommand AddCategoryCommand { get; set; }
        public ICommand ModifyCategoryCommand { get; set; }

        public ICommand DeleteCategoryCommand { get; set; }
        public ICommand DeleteKeywordCommand { get; set; }

        public ICommand SearchCommand { get; set; }
        
    }
}
